<?php
/**
 * Created by JetBrains PhpStorm.
 * User: heimuya
 * Date: 14-1-26
 * Time: 下午1:33
 * 报表控制器类
 */
class StatisticAction extends AdminAction{
	
	public function _initialize(){
		parent::_initialize();
		$this->assign('page', __CLASS__);
	}
	
    /**
     * 订单信息（查询日期之间，指定门店类型[直营店或加盟店]中，所选择门店的所有订单信息）
     */
    public function order(){
	 	$regionList = changeArrayKey(D("Region")->field('id,name')->select());
		$this->assign('regionlist', $regionList);
		$this->assign('method', 'order');
        $this->display();
    }
	
	
    /**
     * 日商品销售表(查询在指定日期时间之间，指定门店地区和类型[直营店或加盟店]，所选门店的日销售商品统计或日商品门店销售比较)
     */
    public function dailysale(){
	 	$regionList = changeArrayKey(D("Region")->field('id,name')->select());
		$this->assign('regionlist', $regionList);
		$this->assign('method', 'dailysale');
        $this->display();
    }
	
    /**
     * 销售类别统计表(查询指定日期时间之间，指定地区和门店类型，所选门店的商品类别统计)
     */
    public function salecategory(){
	 	$regionList = changeArrayKey(D("Region")->field('id,name')->select());
		$this->assign('regionlist', $regionList);
		$this->assign('method', 'salecategory');
        $this->display();
    }
	
    /**
     * 年报表(查询指定年份，指定地区和门店的年报表信息)
     */
    public function yearly(){
	 	$regionList = changeArrayKey(D("Region")->field('id,name')->select());
		$this->assign('regionlist', $regionList);
		$this->assign('method', 'yearly');
        $this->display();
    }
	
    /**
     * 现金日统计报表(查询指定日期时间之间，指定地区和门店类型，所选门店的营业额统计)
     */
    public function cashdaily(){
	 	$regionList = changeArrayKey(D("Region")->field('id,name')->select());
		$this->assign('regionlist', $regionList);
		$this->assign('method', 'cashdaily');
        $this->display();
    }
	
    /**
     * 促销统计报表(查询指定日期时间之间，指定地区和门店类型，所选门店的促销额统计)
     */
    public function sale(){
	 	$regionList = changeArrayKey(D("Region")->field('id,name')->select());
		$this->assign('regionlist', $regionList);
		$this->assign('method', 'sale');
        $this->display();
    }
	
	/**
	 * 日订单报表处理
	 */
	 public function orderjson(){
	 	$postdata = $this->_post();
		$aoColumns = array(L('storename'), L('date'), L('ordercount'), L('totalpay'), L('totaldiscount'), L('withdrawrate'));
		$time = explode('/', str_replace(' ', '', $postdata['daterange']));//起止时间
		$where['time'] = array(array('gt', strtotime($time[0])), array('elt', strtotime($time[1]) + 86400), 'and');
		$tabledata = array('columns' => $aoColumns, 'caption' => array('captionhead' => L('storeorder_statistic'), 'timestart' =>$time[0], 'timeend' => $time[1]));
		$storelist = changeArrayKey($this->storesBelongs($postdata));
		if(isset($postdata['store']) && $postdata['store'] !== '-1'){//若选择了特定的门店
			$where['store'] = $postdata['store'];
		}else{
			$temp = array();
			foreach ($storelist as $value) {
				$temp[] = $value['id'];
			}
			$where['store'] = array('in', $temp);
		}
		//获取满足条件的门店的订单信息
		$orderlist = D('Order')->field('time, total, discount, type, store')->where($where)->select();
		$data = array();
		$withdraw = array();
		foreach ($orderlist as $key => $value) {
			$date = date('Y-m-d', $value['time']);
			if(!isset($data[$date.$value['store']])){
				$withdraw[$date.$value['store']] = ($value['type'] == 'withdraw') ? 1 : 0;
				$data[$date.$value['store']] = array(
					$storelist[$value['store']]['name'],
					$date,
					1,
					intval($value['total']),
					intval($value['discount']),
					$withdraw[$date.$value['store']]
				);
			}else{
				$withdraw[$date.$value['store']] = $withdraw[$date.$value['store']] + (($value['type'] == 'withdraw') ? 1 : 0);
				$temp = array(
					$storelist[$value['store']]['name'],
					$date,
					$data[$date.$value['store']][2] + 1,
					$data[$date.$value['store']][3] + intval($value['total']),
					$data[$date.$value['store']][4] + intval($value['discount']),
					$withdraw[$date.$value['store']] / ($data[$date.$value['store']][2] + 1)
				);
				$data[$date.$value['store']] = $temp;
			}
		}
		$aaData = array();
		foreach ($data as $value) {
			$aaData[] = $value;
		}
		$tabledata['data'] = $aaData;
		
		echo json_encode(array('status' => 200, 'tabledata' => $tabledata));
		exit(0);
	 }

	/**
	 * 日商品销售表
	 */
	 public function dailysalejson(){
	 	$postdata = $this->_post();
		$aoColumns = array(L('storename'), L('date'), L('goodscategory'), L('goodsname'), L('saleinfo'), L('discount'), L('subtotal'));
		$time = explode('/', str_replace(' ', '', $postdata['daterange']));//起止时间
		$where['o.time'] = array(array('gt', strtotime($time[0])), array('elt', strtotime($time[1]) + 86400), 'and');
		$tabledata = array('columns' => $aoColumns, 'caption' => array('captionhead' => L('dailysaletable'), 'timestart' =>$time[0], 'timeend' => $time[1]));
		$storelist = changeArrayKey($this->storesBelongs($postdata));
		if(isset($postdata['store']) && $postdata['store'] !== '-1'){//若选择了特定的门店
			$where['o.store'] = $postdata['store'];
		}else{
			$temp = array();
			foreach ($storelist as $value) {
				$temp[] = $value['id'];
			}
			$where['o.store'] = array('in', $temp);
		}
		//只获取正常订单的统计值
		$where['o.type'] = 'normal';
		//获取满足条件的门店的订单信息
		
    	$orderlist = D("OrderView")->where($where)->select();
		$data = array();
		foreach ($orderlist as $key => $value) {
			if($value['cname'] == '' && $value['fname'] == ''){
				$value['cname'] = '<span class="cred">'.L('deletedata').'</span>';
				$value['fname'] = '<span class="cred">'.L('deletedata').'</span>';
			}
			$date = date('Y-m-d', $value['time']);
			if(!isset($data[$date.$value['store'].$value['fid']])){
				$data[$date.$value['store'].$value['fid']] = array(
					$storelist[$value['store']]['name'],
					$date,
					$value['cname'],
					$value['fname'],
					intval($value['amount']),
					intval($value['discount']),
					intval($value['total'])
				);
			}else{
				$temp = array(
					$storelist[$value['store']]['name'],
					$date,
					$value['cname'],
					$value['fname'],
					$data[$date.$value['store'].$value['fid']][4] + intval($value['amount']),
					$data[$date.$value['store'].$value['fid']][5] + intval($value['discount']),
					$data[$date.$value['store'].$value['fid']][6] + intval($value['total'])
				);
				$data[$date.$value['store'].$value['fid']] = $temp;
			}
		}
		$aaData = array();
		foreach ($data as $value) {
			$aaData[] = $value;
		}
		$tabledata['data'] = $aaData;
		
		echo json_encode(array('status' => 200, 'tabledata' => $tabledata));
		exit(0);
	 }

	/**
	 * 销售类别统计报表
	 */
	 public function salecategoryjson(){
	 	$postdata = $this->_post();
		$aoColumns = array(L('goodscategory'), L('saleinfo'), L('discount'), L('subtotal'), L('salerate'));
		$time = explode('/', str_replace(' ', '', $postdata['daterange']));//起止时间
		$where['o.time'] = array(array('gt', strtotime($time[0])), array('elt', strtotime($time[1]) + 86400), 'and');
		$tabledata = array('columns' => $aoColumns, 'caption' => array('captionhead' => L('salecategorytable'), 'timestart' =>$time[0], 'timeend' => $time[1]));
		if(isset($postdata['store']) && $postdata['store'] !== '-1'){//若选择了特定的门店
			$where['o.store'] = $postdata['store'];
		}else{
			echo json_encode(array('status' => 201, 'errorMsg' => L('storeblank')));
			exit(0);
		}
		//只获取正常订单的统计值
		$where['o.type'] = 'normal';
		//获取满足条件的门店的订单信息
		
    	$orderlist = D("OrderView")->where($where)->select();
		$data = array();
		$count = 0;
		foreach ($orderlist as $key => $value) {
			$count = $count + intval($value['amount']);//计算销售量占比
			if(!isset($data[$value['cid']])){
				$data[$value['cid']] = array(
					$value['cname'],
					intval($value['amount']),
					intval($value['discount']),
					intval($value['total'])
				);
			}else{
				$temp = array(
					$value['cname'],
					$data[$value['cid']][1] + intval($value['amount']),
					$data[$value['cid']][2] + intval($value['discount']),
					$data[$value['cid']][3] + intval($value['total'])
				);
				$data[$value['cid']] = $temp;
			}
		}
		$aaData = array();
		foreach ($data as $value) {
			$value[] = round($value[1] / $count, 3);
			$aaData[] = $value;
		}
		$tabledata['data'] = $aaData;
		
		echo json_encode(array('status' => 200, 'tabledata' => $tabledata));
		exit(0);
	 }

	/**
	 * 现金日报表处理
	 */
	 public function cashdailyjson(){
	 	$postdata = $this->_post();
		$aoColumns = array(L('region'), L('storename'), L('Turnover'));
		$time = explode('/', str_replace(' ', '', $postdata['daterange']));//起止时间
		$where['time'] = array(array('gt', strtotime($time[0])), array('elt', strtotime($time[1]) + 86400), 'and');
		$tabledata = array('columns' => $aoColumns, 'caption' => array('captionhead' => L('cashdailytable'), 'timestart' =>$time[0], 'timeend' => $time[1]));
		$storelist = changeArrayKey($this->storesBelongs($postdata));
		if(isset($postdata['store']) && $postdata['store'] !== '-1'){//若选择了特定的门店
			$where['store'] = $postdata['store'];
		}else{
			$temp = array();
			foreach ($storelist as $value) {
				$temp[] = $value['id'];
			}
			$where['store'] = array('in', $temp);
		}
		$where1['id'] = $postdata['region'];
		$region = D('Region')->field('id, name')->where($where1)->find();
		$region = $region['name'];
		//获取满足条件的门店的订单信息
		$where['type'] = 'normal';
		$orderlist = D('Order')->field('total, discount, store')->where($where)->select();
		$data = array();
		foreach ($orderlist as $key => $value) {
			if(!isset($data[$value['store']])){
				$data[$value['store']] = array(
					$region,
					$storelist[$value['store']]['name'],
					intval($value['total']) - intval($value['discount'])
				);
			}else{
				$temp = array(
					$region,
					$storelist[$value['store']]['name'],
					$data[$value['store']][2] + intval($value['total']) - intval($value['discount'])
				);
				$data[$value['store']] = $temp;
			}
		}
		$aaData = array();
		foreach ($data as $value) {
			$aaData[] = $value;
		}
		$tabledata['data'] = $aaData;
		
		echo json_encode(array('status' => 200, 'tabledata' => $tabledata));
		exit(0);
	 }
	
	/**
	 * 年报表处理
	 */
	 public function yearlyjson(){
	 	$postdata = $this->_post();
		$aoColumns = array(L('month'), L('region'), L('storename'), L('Turnover'));
		$time = array($postdata['year'].'-01-01', $postdata['year'].'-12-31');//起止时间
		$where['time'] = array(array('gt', strtotime($time[0])), array('elt', strtotime($time[1]) + 86400), 'and');
		$tabledata = array('columns' => $aoColumns, 'caption' => array('captionhead' => L('yearlytable'), 'timestart' =>$time[0], 'timeend' => $time[1]));
		$storelist = changeArrayKey($this->storesBelongs($postdata));
		if(isset($postdata['store']) && $postdata['store'] !== '-1'){//若选择了特定的门店
			$where['store'] = $postdata['store'];
		}else{
			$temp = array();
			foreach ($storelist as $value) {
				$temp[] = $value['id'];
			}
			$where['store'] = array('in', $temp);
		}
		$where1['id'] = $postdata['region'];
		$region = D('Region')->field('id, name')->where($where1)->find();
		$region = $region['name'];
		//获取满足条件的门店的订单信息
		$where['type'] = 'normal';
		$orderlist = D('Order')->field('time, total, discount, store')->where($where)->select();
		$data = array();
		foreach ($orderlist as $key => $value) {
			$date = date('Y-m', $value['time']);
			if(!isset($data[$date.$value['store']])){
				$data[$date.$value['store']] = array(
					$date,
					$region,
					$storelist[$value['store']]['name'],
					intval($value['total'])
				);
			}else{
				$temp = array(
					$date,
					$region,
					$storelist[$value['store']]['name'],
					$data[$date.$value['store']][3] + intval($value['total'])
				);
				$data[$date.$value['store']] = $temp;
			}
		}
		$aaData = array();
		foreach ($data as $value) {
			$aaData[] = $value;
		}
		$tabledata['data'] = $aaData;
		
		echo json_encode(array('status' => 200, 'tabledata' => $tabledata));
		exit(0);
	 }
	
	/**
	 * 促销报表处理
	 */
	 public function salejson(){
	 	$postdata = $this->_post();
		$aoColumns = array(L('salename'), L('salecategory'), L('saleinfo'), L('saletotal'));
		$time = explode('/', str_replace(' ', '', $postdata['daterange']));//起止时间
		$where['o.time'] = array(array('gt', strtotime($time[0])), array('elt', strtotime($time[1]) + 86400), 'and');
		$tabledata = array('columns' => $aoColumns, 'caption' => array('captionhead' => L('saletable'), 'timestart' =>$time[0], 'timeend' => $time[1]));
		$storelist = changeArrayKey($this->storesBelongs($postdata));
		if(isset($postdata['store']) && $postdata['store'] !== '-1'){//若选择了特定的门店
			$where['o.store'] = $postdata['store'];
		}else{
			$temp = array();
			foreach ($storelist as $value) {
				$temp[] = $value['id'];
			}
			$where['o.store'] = array('in', $temp);
		}
		$where1['id'] = $postdata['region'];
		$region = D('Region')->field('id, name')->where($where1)->find();
		$region = $region['name'];
		//获取满足条件的门店的订单信息
		$where['o.type'] = 'normal';
		$where['od.onsale'] = 'y';
		$where['od.saleid'] = array('NEQ', '');
		$orderlist = D("SaleorderView")->where($where)->group('od.saleid')->select();
		$aaData = array();
		foreach ($orderlist as $key => $value) {
			$aaData[] = array(
				$value['sname'],
				$value['scname'],
				$value['amount'],
				$value['total']
			);
		}
		$tabledata['data'] = $aaData;
		
		echo json_encode(array('status' => 200, 'tabledata' => $tabledata));
		exit(0);
	 }
	 
	/**
	 * 获取对应区域对应类型的门店
	 */
	 private function storesBelongs($postdata){
		$where = array();
		if(isset($postdata['region']) && $postdata['region'] !== '-1'){
			$where['region'] = $postdata['region'];
		}
		if(isset($postdata['storetype']) && $postdata['storetype'] !== '-1'){
			$where['type'] = ($postdata['storetype'] == '1') ? 'direct' : 'join';
		}
		return D('Store')->field('id,name')->where($where)->select();
	 }
	 
	/**
	 * ajax获取对应区域对应类型的门店
	 */
	 public function storesjson(){
	 	$postdata = $this->_post();
	 	$result = $this->storesBelongs($postdata);
		$content = '<option value="-1">'.L('select').'...</option>';
		if($result){
			foreach ($result as $value) {
				$content .= '<option value="'.$value['id'].'">'.$value['name'].'</option>';
			}
		}
		echo json_encode(array('status' => 200, 'data' => $content));
		exit(0);
	 }
	
    /**
     * 后台首页
     */
    public function index(){
        $this->display();
    }
}